package com.moon;

import io.rong.imkit.RongIM;

import java.util.ArrayList;
import java.util.Set;

import me.leolin.shortcutbadger.ShortcutBadger;

import cn.yueliangbaba.R;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.RequestParams;
import com.sys.DemoApp;
import com.umeng.message.UmengRegistrar;
import com.util.BadgeUtil;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.util.ToastUtil;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainPageActivity extends BaseActivity implements OnClickListener{
	static public MainPageActivity mMainPageActivity = null;
	
	int mSelected = 0;
	 private ViewPager mPager;  
	 private ArrayList<FragmentDynamic> fragmentList;  
	 int mUnreadMsg = 0;
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_page);
		
		findViewById(R.id.left).setVisibility(View.VISIBLE);
		((Button)findViewById(R.id.left)).setCompoundDrawablesWithIntrinsicBounds(R.drawable.btn_filter, 0, 0, 0);
		
		((Button)findViewById(R.id.right)).setCompoundDrawablesWithIntrinsicBounds(R.drawable.btn_identity, 0, 0, 0);
		((TextView) findViewById(R.id.center)).setText("班级圈");
		
		((Button)findViewById(R.id.tab0)).setSelected(true);
	
		findViewById(R.id.tab0).setOnClickListener(this);
		findViewById(R.id.tab1).setOnClickListener(this);
		findViewById(R.id.tab2).setOnClickListener(this);
		findViewById(R.id.tab3).setOnClickListener(this);
		findViewById(R.id.left).setOnClickListener(this);
		findViewById(R.id.right).setOnClickListener(this);
		
		sendRequest();
		initFragment();
		
		((DemoApp)getApplicationContext()).addActivity(this);
		mMainPageActivity = this;
		
		if(MainTabActivity.mMainTabActivity != null) MainTabActivity.mMainTabActivity.setChatMsg();
	}
	
	private void sendRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, false, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);
				if (ruser.getString("statusCode").equals("0")) {
					JSONObject member = ruser.getJSONObject("member");
					
					PreferencesUtils.putString(MainPageActivity.this, "member", JSON.toJSONString(member));
					PreferencesUtils.putString(MainPageActivity.this, "classes", JSON.toJSONString(member.getJSONArray("classes")));
					PreferencesUtils.putString(MainPageActivity.this, "children", JSON.toJSONString(member.getJSONArray("children")));
				}
				else 
				{
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			}
		};
		
		RequestParams params = new RequestParams();
		params.put("phonenumber", PreferencesUtils.getString(this, "username"));
		params.put("password", PreferencesUtils.getString(this, "password"));
		params.put("android_token", UmengRegistrar.getRegistrationId(this));//ios_token
		MgqRestClient.get("member_login", params, loginHandler);
	}
	
	public void setBadgeRequest(String response) {
		findViewById(R.id.new0).setVisibility(View.INVISIBLE);
		findViewById(R.id.new1).setVisibility(View.INVISIBLE);
		findViewById(R.id.new2).setVisibility(View.INVISIBLE);
		findViewById(R.id.new3).setVisibility(View.INVISIBLE);
		findViewById(R.id.new5).setVisibility(View.INVISIBLE);
		findViewById(R.id.new6).setVisibility(View.INVISIBLE);
		findViewById(R.id.new7).setVisibility(View.INVISIBLE);
		findViewById(R.id.new8).setVisibility(View.INVISIBLE);

		mUnreadMsg = 0;
		if(response.equals("[]"))
		{
			setIconNumber();
			if(MainTabActivity.mMainTabActivity != null) MainTabActivity.mMainTabActivity.setNewMsg(0, false);
			return;
		}
		
		JSONObject ruser = JSON.parseObject(response);
		boolean firstRedDot = false;
		
		Set<String> array = ruser.keySet();
		for(String type : array)
		{
			JSONObject obj = ruser.getJSONObject(type);
			String number = obj.getString("number");
			
			if(type.equals("1"))
			{
				if(number != null && number.length() > 0) 
				{
					mUnreadMsg += Integer.valueOf(number);
					findViewById(R.id.new1).setVisibility(View.VISIBLE);
					((TextView)findViewById(R.id.new1)).setText(number);
				}
			}
			else if(type.equals("2"))
			{
				if(number != null && number.length() > 0) 
				{
					mUnreadMsg += Integer.valueOf(number);
					findViewById(R.id.new2).setVisibility(View.VISIBLE);
					((TextView)findViewById(R.id.new2)).setText(number);
				}
			}
			else if(type.equals("4"))
			{
				findViewById(R.id.new0).setVisibility(View.VISIBLE);
				if(number != null && number.length() > 0)
				{
					mUnreadMsg += Integer.valueOf(number);
					((TextView)findViewById(R.id.new0)).setText(number);
				}
				else
				{
					firstRedDot = true;
					((TextView)findViewById(R.id.new0)).setText("");
				}
			}
			else
			{
				if(number != null && number.length() > 0)
				{
					mUnreadMsg += Integer.valueOf(number);
					findViewById(R.id.new3).setVisibility(View.VISIBLE);
					((TextView)findViewById(R.id.new3)).setText(number);
				}
			}
		}
		
		if(MainTabActivity.mMainTabActivity != null) 
		{
			MainTabActivity.mMainTabActivity.setNewMsg(mUnreadMsg, firstRedDot);
		}
		
		setIconNumber();
	}
	
	public void setIconNumber()
	{
		int num = RongIM.getInstance().getRongIMClient().getTotalUnreadCount();
		try{
			BadgeUtil.setBadgeCount(getApplicationContext(), mUnreadMsg + num);
			if(!ShortcutBadger.applyCount(this, mUnreadMsg + num))
				BadgeUtil.setBadgeCount(this, mUnreadMsg + num);
		}
		catch(Exception e){}
	}
	
	@Override
	protected void onDestroy() {
		((DemoApp)getApplicationContext()).removeActivity(this);
		super.onDestroy();
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		
		if(((DemoApp)getApplicationContext()).mTab > -1)
		{
			((Button)findViewById(R.id.tab0 + 4*mSelected)).setSelected(false);
			((Button)findViewById(R.id.tab0 + 4*mSelected)).setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
			((Button)findViewById(R.id.tab0 + 4*((DemoApp)getApplicationContext()).mTab)).setSelected(true);
			((Button)findViewById(R.id.tab0 + 4*((DemoApp)getApplicationContext()).mTab)).setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.line);
			mSelected = ((DemoApp)getApplicationContext()).mTab;
			mPager.setCurrentItem(((DemoApp)getApplicationContext()).mTab,true);
			
			((DemoApp)getApplicationContext()).mTab = -1;
		}
		
		fragmentList.get(mSelected).mAdapter.notifyDataSetChanged();
	}
	
	void initFragment()
	{
		mPager = (ViewPager)findViewById(R.id.viewpager);  
		fragmentList = new ArrayList<FragmentDynamic>();  
        fragmentList.add(new FragmentDynamic(this,4));  
        fragmentList.add(new FragmentDynamic(this,1));  
        fragmentList.add(new FragmentDynamic(this,2));  
        fragmentList.add(new FragmentDynamic(this,5));  
        mPager.setAdapter(new MyFragmentPagerAdapter());  
        mPager.setOnPageChangeListener(new MyOnPageChangeListener());//页面变化时的监听器  
        mPager.setCurrentItem(0);
	}

	public class MyOnPageChangeListener implements OnPageChangeListener{  
        @Override  
        public void onPageScrolled(int arg0, float arg1, int arg2) {  
        }  
          
        @Override  
        public void onPageScrollStateChanged(int arg0) {  
        }  
          
        @Override  
        public void onPageSelected(int arg0) {  
        	((Button)findViewById(R.id.tab0 + 4*mSelected)).setSelected(false);
			((Button)findViewById(R.id.tab0 + 4*mSelected)).setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
			mSelected = arg0;
			((Button)findViewById(R.id.tab0 + 4*mSelected)).setSelected(true);
			((Button)findViewById(R.id.tab0 + 4*mSelected)).setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.line);
        
			fragmentList.get(mSelected).initData();
        }
	}
	
	public class MyFragmentPagerAdapter extends PagerAdapter{

		@Override
		public int getCount() {
			return fragmentList.size();
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(fragmentList.get(arg1));
			return fragmentList.get(arg1);
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView((View) arg2);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}
	}  
	
	@Override
	public void onClick(View arg0) {
		int viewId = arg0.getId();
		switch(viewId)
		{
		case R.id.tab0:
		case R.id.tab1:
		case R.id.tab2:
		case R.id.tab3:
			((Button)findViewById(R.id.tab0 + 4*mSelected)).setSelected(false);
			((Button)findViewById(R.id.tab0 + 4*mSelected)).setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
			((Button)arg0).setSelected(true);
			((Button)arg0).setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.line);
			mSelected = (viewId - R.id.tab0)/4;
			mPager.setCurrentItem((viewId - R.id.tab0)/4,true);
			
//			fragmentList.get(mSelected).initData();
			break;
			
		case R.id.right:
		{
			Intent intent = new Intent(this,DistributeActivity.class);
			startActivity(intent);
		}
			break;
			
		case R.id.left:
			try
			{
				fragmentList.get(mSelected).showImagePicker();
			}
			catch(Exception e){}
			break;
		}
	}
	
	public void setDotInVisible(int index)
	{
		if(index == 1) findViewById(R.id.new6).setVisibility(View.INVISIBLE);
		if(index == 2) findViewById(R.id.new7).setVisibility(View.INVISIBLE);
		if(index == 3) findViewById(R.id.new8).setVisibility(View.INVISIBLE);
	}
	
	public void autoRefresh(int tab)
	{
		((Button)findViewById(R.id.tab0 + 4*mSelected)).setSelected(false);
		((Button)findViewById(R.id.tab0 + 4*mSelected)).setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
		mSelected = tab;
		((Button)findViewById(R.id.tab0 + 4*mSelected)).setSelected(true);
		((Button)findViewById(R.id.tab0 + 4*mSelected)).setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.line);
		mPager.setCurrentItem(mSelected,true);
		fragmentList.get(mSelected).initData();
	}
	
	public void autoRefresh()
	{
//		onClick(findViewById(R.id.tab0));
		fragmentList.get(mSelected).initData();
	}
	
	private long exitTime = 0;
	public void exitApp() {
		if ((System.currentTimeMillis() - exitTime) > 2000) 
		{
			Toast.makeText(this, "再按一次退出 应用", Toast.LENGTH_SHORT).show();
			exitTime = System.currentTimeMillis();
		} 
		else
		{
			finish();
		}
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {// 捕捉返回键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exitApp();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
